<template>
  <div class="receipt-list-container">
    <div class="page-header">
      <h2 class="page-title">收货单管理</h2>
      <el-button type="primary" @click="createReceipt">
        <el-icon>
          <Plus/>
        </el-icon>
        新增收货单
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline label-width="80px" @keyup.enter="handleSearch">
        <el-form-item label="收货单号">
          <el-input v-model="searchForm.receiptNumber" clearable placeholder="请输入收货单号"></el-input>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNumber" clearable placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplierName" clearable placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态" style="width: 180px">
            <el-option label="待验收" value="待验收"></el-option>
            <el-option label="已验收" value="已验收"></el-option>
            <el-option label="已开票" value="已开票"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货日期">
          <el-date-picker
              v-model="searchForm.dateRange"
              :shortcuts="dateShortcuts"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-operations">
        <el-tooltip content="只能批量删除状态为待验收的收货单" placement="top">
          <el-button
              :disabled="!hasSelectableDeletableReceipts"
              type="danger"
              @click="batchDelete"
          >
            <el-icon>
              <Delete/>
            </el-icon>
            批量删除
          </el-button>
        </el-tooltip>
        <el-button type="success" @click="exportAll">
          <el-icon>
            <Download/>
          </el-icon>
          导出全部
        </el-button>
      </div>

      <el-table
          v-loading="loading"
          :data="receiptList"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            :selectable="row => row.status === '待验收'"
            type="selection"
            width="55"
        ></el-table-column>
        <el-table-column label="收货单编号" min-width="120" prop="receiptNumber"></el-table-column>
        <el-table-column label="订单编号" min-width="120" prop="orderNumber"></el-table-column>
        <el-table-column label="供应商" min-width="150" prop="supplierName"></el-table-column>
        <el-table-column label="收货日期" prop="receiptDate" width="110"></el-table-column>
        <el-table-column label="状态" prop="status" width="110">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已验收' ? 'success' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收货金额" prop="totalAmount" width="150">
          <template #default="scope">
            {{ formatCurrency(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <div class="action-buttons">
              <el-button class="blue-button" size="small" type="primary" @click="viewReceipt(scope.row)">查看
              </el-button>
              <el-button
                  :class="{'blue-button': scope.row.status === '待验收', 'disabled-button': scope.row.status !== '待验收'}"
                  :disabled="scope.row.status !== '待验收'"
                  size="small"
                  type="primary"
                  @click="editReceipt(scope.row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                  title="确定删除此收货单吗？"
                  @confirm="handleDeleteReceipt(scope.row.id)"
              >
                <template #reference>
                  <el-button
                      :class="{'blue-button': scope.row.status === '待验收', 'disabled-button': scope.row.status !== '待验收'}"
                      :disabled="scope.row.status !== '待验收'"
                      size="small"
                      type="danger"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Download, Plus, Refresh, Search} from '@element-plus/icons-vue';
import {
  batchDeleteReceipt,
  deleteReceipt,
  exportReceipt,
  findReceiptsByOrderNumber,
  getReceiptList
} from '@/api/receipt.ts';

const router = useRouter();
const loading = ref(false);
const receiptList = ref<any[]>([]);
const selectedReceipts = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 计算是否有可删除的收货单（状态为待验收）
const hasSelectableDeletableReceipts = computed(() => {
  return selectedReceipts.value.some(receipt => receipt.status === '待验收');
});

// 搜索表单
const searchForm = reactive({
  receiptNumber: '',
  orderNumber: '',
  supplierName: '',  // 添加供应商字段
  status: '',
  dateRange: [] as Date[]
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];

// 页面加载时获取数据
onMounted(() => {
  fetchReceiptList();
});

// 获取发货单列表
const fetchReceiptList = async () => {
  loading.value = true;
  try {
    // 如果按订单编号搜索，使用专门的API
    if (searchForm.orderNumber && searchForm.orderNumber.trim() !== '') {
      const res = await findReceiptsByOrderNumber(searchForm.orderNumber.trim());

      if (res && res.code === 200) {
        if (Array.isArray(res.data)) {
          receiptList.value = res.data;
          total.value = res.data.length;
        } else if (res.data && Array.isArray(res.data.records)) {
          receiptList.value = res.data.records;
          total.value = res.data.total || res.data.records.length;
        } else {
          receiptList.value = [];
          total.value = 0;
          ElMessage.warning('未找到符合条件的收货单');
        }
        loading.value = false;
        return;
      }
    }

    // 构建查询参数
    const queryParams: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    // 添加搜索条件
    if (searchForm.receiptNumber) {
      queryParams.receiptNumber = searchForm.receiptNumber;
    }

    // 不再添加orderNumber参数，因为后端API不支持
    // if (searchForm.orderNumber) {
    //   queryParams.orderNumber = searchForm.orderNumber;
    // }

    if (searchForm.supplierName) {
      queryParams.supplierName = searchForm.supplierName;
    }

    if (searchForm.status) {
      queryParams.status = searchForm.status;
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      queryParams.startDate = formatDate(searchForm.dateRange[0]);
      queryParams.endDate = formatDate(searchForm.dateRange[1]);
    }

    // 发送请求前先清空当前列表
    receiptList.value = [];

    const res = await getReceiptList(queryParams);

    if (res.code === 200) {
      // 标准分页格式(records + total)
      if (res.data && res.data.records && Array.isArray(res.data.records)) {
        receiptList.value = res.data.records;
        total.value = res.data.total || 0;
      }
      // records数组直接在data中
      else if (res.data && Array.isArray(res.data.records)) {
        receiptList.value = res.data.records;
        total.value = res.data.total || receiptList.value.length;
      }
      // 列表格式(list + total)
      else if (res.data && res.data.list && Array.isArray(res.data.list)) {
        receiptList.value = res.data.list;
        total.value = res.data.total || res.data.list.length;
      }
      // data本身是数组
      else if (Array.isArray(res.data)) {
        receiptList.value = res.data;
        total.value = res.data.length;
      }
      // 空数据或其他格式
      else {
        console.warn('未能识别的数据格式:', res.data);
        receiptList.value = [];
        total.value = 0;
        ElMessage.warning('未找到符合条件的收货单数据');
      }

      // 如果读取到空列表但后端没有正确设置total
      if (receiptList.value.length === 0 && total.value > 0 && currentPage.value > 1) {
        // 返回上一页
        currentPage.value--;
        fetchReceiptList();
        return;
      }
    } else {
      console.error('获取收货单列表失败:', res.message);
      ElMessage.error(res.message || '获取收货单列表失败');
      receiptList.value = [];
      total.value = 0;
    }
  } catch (error: any) {
    console.error('获取收货单列表失败:', error);
    // 详细记录错误信息
    console.error('错误类型:', error.name);
    console.error('错误消息:', error.message);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应数据:', error.response.data);
    }

    receiptList.value = [];
    total.value = 0;

    // 显示友好的错误消息
    ElMessage.error({
      message: `获取收货单列表失败: ${error.message || '未知错误'}`,
      duration: 5000
    });
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (date: Date): string => {
  if (!date) return '';
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  fetchReceiptList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.receiptNumber = '';
  searchForm.orderNumber = '';
  searchForm.supplierName = ''; // 确保清空供应商字段
  searchForm.status = '';
  searchForm.dateRange = [];
  handleSearch();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  fetchReceiptList();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchReceiptList();
};

// 表格多选处理
const handleSelectionChange = (selection: any[]) => {
  selectedReceipts.value = selection;
};

// 创建新发货单
const createReceipt = () => {
  router.push('/dashboard/receipt-create');
};

// 查看发货单详情
const viewReceipt = (row: any) => {
  router.push(`/dashboard/receipt-detail/${row.id}`);
};

// 编辑发货单
const editReceipt = (row: any) => {
  router.push(`/dashboard/receipt-edit/${row.id}`);
};

// 删除发货单
const handleDeleteReceipt = async (id: string) => {
  try {
    await deleteReceipt(id);
    ElMessage.success('删除成功');
    fetchReceiptList(); // 重新加载数据
  } catch (error) {
    console.error('删除发货单失败:', error);
    ElMessage.error('删除发货单失败，请重试');
  }
};

// 批量删除
const batchDelete = () => {
  // 过滤出可删除的收货单（状态为待验收）
  const deletableReceipts = selectedReceipts.value.filter(receipt => receipt.status === '待验收');

  if (deletableReceipts.length === 0) {
    ElMessage.warning('没有可删除的收货单，只有待验收状态的收货单可以删除');
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的${deletableReceipts.length}个收货单吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = deletableReceipts.map(item => item.id);
      await batchDeleteReceipt(ids);
      ElMessage.success('批量删除成功');
      fetchReceiptList(); // 重新加载数据
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败，请重试');
    }
  }).catch(() => {
    // 取消操作
  });
};

// 导出全部收货单
const exportAll = async () => {
  try {
    // 先检查是否已经在执行导出操作
    if (loading.value) {
      ElMessage.warning('导出操作正在进行中，请勿重复点击');
      return;
    }

    loading.value = true;
    ElMessage.info('正在准备导出数据，请稍候...');

    // 检查token是否存在
    const token = sessionStorage.getItem('token');
    if (!token) {
      ElMessage.error('您未登录或登录已过期，请先登录系统');
      router.push('/login');
      return;
    }

    // 创建一个新对象而不是直接修改searchForm
    const params: Record<string, any> = {};

    // 复制需要的字段
    if (searchForm.receiptNumber) params.receiptNumber = searchForm.receiptNumber;
    if (searchForm.orderNumber) params.orderNumber = searchForm.orderNumber;
    if (searchForm.supplierName) params.supplierName = searchForm.supplierName;
    if (searchForm.status) params.status = searchForm.status;

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = formatDate(searchForm.dateRange[0]);
      params.endDate = formatDate(searchForm.dateRange[1]);
    }

    // 发起导出请求，指定responseType为blob
    const res = await exportReceipt(params);

    // 检查响应状态
    if (!res.success) {
      ElMessage.error(`导出失败: ${res.message}`);
      console.error('导出失败:', res);
      return;
    }

    // 判断响应类型并处理
    if (res.data instanceof Blob) {
      // 检查Blob类型，确保是Excel文件
      if (res.data.type.includes('spreadsheetml') ||
          res.data.type === 'application/octet-stream' ||
          res.data.type === 'application/vnd.ms-excel') {
        // 创建下载链接
        const blob = res.data;
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `收货单列表_${new Date().getTime()}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        ElMessage.success('导出成功');
      } else {
        // 如果不是Excel，可能是错误消息
        const reader = new FileReader();
        reader.onload = () => {
          try {
            // 尝试解析为JSON
            const result = JSON.parse(reader.result as string);
            console.error('导出返回错误JSON:', result);
            ElMessage.error(`导出失败: ${result.message || '未知错误'}`);
          } catch (e) {
            // 不是JSON，显示通用错误
            console.error('导出返回未知格式:', reader.result);
            ElMessage.error('导出失败，返回格式不正确');
          }
        };
        reader.onerror = (e) => {
          console.error('读取Blob内容失败:', e);
          ElMessage.error('导出失败，无法读取响应内容');
        };
        reader.readAsText(res.data);
      }
    } else {
      console.error('导出响应不是Blob类型:', typeof res.data);
      ElMessage.error('导出失败，响应格式不正确');
    }
  } catch (error: any) {
    console.error('导出失败:', error);
    // 特别处理401错误，避免重复显示错误信息和无限循环
    if (error.code === 401) {
      ElMessage.error('导出失败: 登录已过期，请重新登录');
      // 不再自动跳转到登录页面，避免循环
    } else {
      ElMessage.error(`导出失败: ${error.message || '请稍后重试'}`);
    }
  } finally {
    loading.value = false;
  }
};

// 格式化金额为货币格式
const formatCurrency = (value: number) => {
  if (!value && value !== 0) return '';
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2
  }).format(value);
};

// 获取状态类型
// const getStatusType = (status: string) => {
//   switch (status) {
//     case '待验收':
//       return 'warning';
//     case '已验收':
//       return 'success';
//     default:
//       return 'info';
//   }
// };

// 查看订单详情
// const viewOrder = (orderId: string) => {
//   if (orderId) {
//     router.push(`/dashboard/order-detail/${orderId}`);
//   } else {
//     ElMessage.warning('该收货单未关联订单');
//   }
// };
</script>

<style scoped>
.receipt-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  /* 添加固定高度和溢出处理，防止搜索条件栏位置变化 */
  min-height: 80px;
}

.table-card {
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 根据参考图修改的样式 */
:deep(.el-card) {
  border: none;
}

:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-button--primary) {
  background-color: #1890FF;
}

:deep(.el-pagination) {
  padding: 20px 0;
}

:deep(.el-tag) {
  border-radius: 12px;
  padding: 0 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.blue-button {
  background-color: #1890FF;
  border: none;
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
}

.disabled-button {
  background-color: rgba(24, 144, 255, 0.5);
  border: none;
  color: #ffffff;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: not-allowed;
}

.disabled-button[type="danger"] {
  background-color: rgba(245, 108, 108, 0.5);
}

:deep(.el-form) {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

:deep(.el-form-item) {
  margin-bottom: 10px;
  margin-right: 10px;
}

:deep(.el-form-item__content) {
  min-height: 32px;
  display: flex;
  align-items: center;
}

/* 订单链接样式 */
.order-link {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
  transition: all 0.3s ease;
  color: #606266;
}

.order-link:hover {
  color: #67C23A;
  transform: translateX(2px);
}

.order-link .el-icon {
  font-size: 14px;
  margin-right: 2px;
  color: #67C23A;
}

.no-order {
  color: #909399;
  font-size: 14px;
}

/* 表格内容垂直居中 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  height: 100%;
}

/* 优化表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 优化表格内容间距 */
:deep(.el-table .cell) {
  padding: 0 12px;
}

/* 优化表格边框和分割线 */
:deep(.el-table) {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #EBEEF5;
}

:deep(.el-table--border .el-table__header-wrapper) {
  border-bottom: 1px solid #EBEEF5;
}

/* 优化表格头部样式 */
:deep(.el-table__header-wrapper th) {
  background-color: #F5F7FA;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

/* 优化表格斑马纹 */
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #FAFAFA;
}

/* 优化表格hover效果 */
:deep(.el-table__body tr:hover > td) {
  background-color: #F5F7FA !important;
}

/* 按钮样式 */
:deep(.el-button--danger) {
  background-color: #F56C6C !important;
  border-color: #F56C6C !important;
}

:deep(.el-button--success) {
  background-color: #67C23A !important;
  border-color: #67C23A !important;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989 !important;
  border-color: #f78989 !important;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61 !important;
  border-color: #85ce61 !important;
}

:deep(.el-button--danger:disabled) {
  background-color: #fab6b6 !important;
  border-color: #fab6b6 !important;
  color: white !important;
}
</style> 